import React, { useEffect, useState, useImperativeHandle } from 'react';
import { Button } from 'antd';
import { randomKey } from '../../../../utils/utils';
import WarnConditionGroup from './WarnConditionGroup';
import './index.less';

const WarnConditions = (props) => {
  const { value, onChange, createRef } = props;
  const [data, setData] = useState([]);

  useEffect(() => {
    if (value && value.length) {
      setData(getInitData(value));
    } else {
      addGroup(true);
    }
  }, []);

  // 初始化data
  const getInitData = (value) =>
    value.map((item) => {
      item.id = item.id || randomKey();
      item.conditions = item.conditions.map((item) => {
        item.id = item.id || randomKey();
        return item;
      });
      return item;
    });

  useImperativeHandle(createRef, () => ({
    // 暴露方法给父组件,收集验证值
    getValue: (cb) => {
      const isValidate = validateData(); // 验证数据
      if (isValidate) {
        cb(null, data);
      } else {
        cb(true, data);
      }
    },
  }));

  const validateData = () => {
    data.forEach((item) => {
      item.conditions.forEach((item) => {
        if (!item.left_var_name) {
          throw '请选择左变量指标';
        }
        if (!item.operator) {
          throw '请选择条件';
        }
      });
    });
    return true;
  };

  //添加组
  const addGroup = (isFirst) => {
    const group = {
      junction_type: isFirst ? 'none' : 'and',
      conditions: [
        {
          junction_type: 'none',
          left_var_code: '',
          left_var_name: '',
          left_var_type: 'feature', // 左变量类型 默认 feature
          right_var_type: 'literal', // 右变量类型 默认 literal
          id: randomKey(),
        },
      ],
      id: randomKey(),
    };
    if (isFirst) {
      setData([group]);
      onChange && onChange([group]);
    } else {
      const tempData = [...data];
      tempData.push(group);
      setData(tempData);
      onChange && onChange(tempData);
    }
  };

  // 删除组
  const onGroupDel = (index) => {
    const tempData = [...data];
    tempData.splice(index, 1);
    setData(tempData);
    onChange && onChange(tempData);
  };

  const handleGroupChange = (value, id) => {
    const tempData = [...data];
    tempData.forEach((item, index) => {
      if (item.id === id) {
        tempData[index] = value;
      }
    });
    setData(tempData);
    onChange && onChange(tempData);
  };

  return (
    <div className='warn-condition'>
      {data.map((item, index) => (
        <WarnConditionGroup
          {...props}
          isFirst={!!index}
          value={item}
          key={item.id}
          isDelBtn={!!index}
          onGroupDel={() => onGroupDel(index)}
          onChange={(value) => handleGroupChange(value, item.id)}
        />
      ))}
      <div className='warn-condition-add'>
        <Button onClick={() => addGroup()}>添加条件组</Button>
      </div>
    </div>
  );
};

export default WarnConditions;
